package com.hmdp.utils;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWork {
    private static final long BEGIN_TIMESTAMP = 1735689600L; //2023-01-01 00:00:00
    private static final int COUNT_BITS = 32;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    //keyPrefix 业务标识
    public Long nextId(String keyPrefix){
        //1.生成时间戳
        LocalDateTime time = LocalDateTime.now();
        long nowSecond = time.toEpochSecond(ZoneOffset.UTC);
        long timestemp = nowSecond - BEGIN_TIMESTAMP;
        //2.生成序列号
        //获取当前日期
        String data = time.format(DateTimeFormatter.ofPattern("YYYY:MM:dd"));
        Long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + data);//自增
        //3.拼接并返回
        return timestemp << COUNT_BITS | count;
    }


}
